
const LEFT_MOUSE_KEY = 0;

class MouseInput{

    constructor(gameApp) {

        this._gameApp = gameApp;
        let canvas = gameApp.canvas;

        canvas.addEventListener('mousedown',this._onMouseDown.bind(this),false);

        // 防止 mouseup 事件不执行
        canvas.addEventListener('blur',this._onBlur.bind(this),false);
        canvas.addEventListener('mouseout',this._onMouseOut.bind(this),false);
        canvas.addEventListener('mouseenter',this._onMouseEnter.bind(this),false);

        this._func_mouse_move = null;
        this._func_mouse_up = null;
        this.bHasFocus = false;
    }

    _onMouseEnter(){
        console.log(`_onMouseEnter called!`);
        this._gameApp.canvas.focus();
        this.bHasFocus = true;
    }

    _onBlur(e){
        if(this._func_mouse_move || this._func_mouse_up){
            this._onMouseUp(e);
        }
    }

    _onMouseOut(e){
        console.log(`_onMouseOut called!`);
        this.bHasFocus = false;
        if(this._func_mouse_move || this._func_mouse_up){
            this._onMouseUp(e);
        }
    }

    _onMouseDown(e){
        console.log('mouse down!');

        if(!this.bHasFocus){
            return;
        }

        // 只启用鼠标左键
        if(e.button === LEFT_MOUSE_KEY){

            let canvas = this._gameApp.canvas;

            // 左键
            this._func_mouse_move = this._onMouseMove.bind(this);
            this._func_mouse_up = this._onMouseUp.bind(this);
            canvas.addEventListener('mousemove',this._func_mouse_move,false);
            canvas.addEventListener('mouseup',this._func_mouse_up,false);
            this._gameApp.onMouseDown(e);
        }
    }

    _onMouseMove(e){ /* eslint-disable-line */
        this._gameApp.onMouseMove(e);
    }
    _onMouseUp(e){
        this.cancelMouseListener();
        this._gameApp.onMouseUp(e);
    }

    cancelMouseListener(){
        let canvas = this._gameApp.canvas;
        if(this._func_mouse_move){
            console.log('remove move');
            canvas.removeEventListener('mousemove',this._func_mouse_move);
            this._func_mouse_move = null;
        }
        if(this._func_mouse_up){
            console.log('remove up');
            canvas.removeEventListener('mouseup',this._func_mouse_up);
            this._func_mouse_up = null;
        }
    }
}

module.exports = MouseInput;
